package com.ebupt.migu.music.schedule.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ebupt.migu.music.schedule.entity.pubBroadcastingActTask.BroadcastActivityInfoVo;
import com.ebupt.migu.music.schedule.entity.pubBroadcastingActTask.BroadcastCustomerFileVo;
import com.ebupt.migu.music.schedule.entity.pubBroadcastingActTask.BroadcastCustomerTagVo;
import com.ebupt.migu.music.schedule.mapper.PubBroadcastingActTaskMapper;
import com.ebupt.migu.music.schedule.service.PubBroadcastingActTaskService;
import com.ebupt.migu.music.util.constant.CommonConstant;
import com.ebupt.migu.music.util.enumeration.BroadcastCustomerTagEnum;
import com.ebupt.migu.music.util.exception.MyException;
import com.ebupt.migu.music.util.fileUtil.CSVUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PubBroadcastingActTaskServiceImpl implements PubBroadcastingActTaskService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PubBroadcastingActTaskMapper pubBroadcastingActTaskMapper;

    /**
     * 启动公播平台活动
     * 每2钟执行一次定时任务
     */
    @Override
    @Transactional(rollbackFor = MyException.class)
    public void startActivity() {
        //查询要启动的活动
        log.info("查询要启动的活动");
        List<BroadcastActivityInfoVo> startAct = pubBroadcastingActTaskMapper.startOrStopAct("1");
        if (startAct !=null && startAct.size()>0){
            log.info("要启动的活动个数=="+startAct.size());
            for (BroadcastActivityInfoVo infoVo:startAct){
                //客群类型：1-标签客群；2-文件上传【商户ID】；3-手工录入【商户ID】4-全量标签
                String customerType = infoVo.getCustomerType();
                String activityId = infoVo.getActivityId();
                //用来存储活动有哪些标签模块
                List<String> tagModuleList = new ArrayList<>();
                if ("1".equals(customerType)){
                    log.info("组装标签客群==="+activityId);
                   //查询标签
                    List<BroadcastCustomerTagVo> tagVos = pubBroadcastingActTaskMapper.broadcastCustomerTag(activityId);
                    for (int i=1;i<=4;i++){
                        //标签模块：1-店铺标签；2-音乐馆标签；3-语音播报标签；4-套餐标签；
                        String tagModule = String.valueOf(i);
                        Optional<BroadcastCustomerTagVo> first = tagVos.stream()
                                .filter(e -> e.getTagModule().equals(tagModule)).findFirst();
                        //将公播平台标签客群存到redis
                        // public_broadcast_customer_tag表里面的数据
                        if (first.isPresent()){
                            tagModuleList.add(tagModule);
                            BroadcastCustomerTagVo broadcastCustomerTagVo = first.get();
                            String tagPath = broadcastCustomerTagVo.getTagPath();
                            BroadcastCustomerTagEnum byTagModule = BroadcastCustomerTagEnum.getByTagModule(broadcastCustomerTagVo.getTagModule());
                            String redisStr = byTagModule.getRedisStr();
                            redisTemplate.opsForSet().add(activityId+"_"+redisStr,tagPath.split(CommonConstant.pubBroadcastSplit));
                        }
                    }
                }else if ("2".equals(customerType)){
                    log.info("文件上传【商户ID】==="+activityId);
                    //获取用户上传的CSV地址
                    BroadcastCustomerFileVo fileVos = pubBroadcastingActTaskMapper.broadcastCustomerFile(activityId);
                    String filePath = fileVos.getFileRename();
                    //解析用户上传的CSV文件
                    if (!StringUtils.isBlank(filePath)){
                        List<String[]> strings = CSVUtils.csvRead(filePath,',');
                        if (strings !=null && strings.size()>0){
                            List<String> collect = strings.stream().map(e -> e[0]).collect(Collectors.toList());
                            redisTemplate.opsForSet().add(activityId+"_"+CommonConstant.customerFileRedis,collect.toArray());
                        }
                    }
                }else if ("3".equals(customerType)){
                    log.info("手工录入==="+activityId);
                    //公播平台手工录入客群
                    List<String> inputVo = pubBroadcastingActTaskMapper.broadcastCustomerInput(activityId);
                    if (inputVo !=null && inputVo.size()>0){
                        redisTemplate.opsForSet().add(activityId+"_"+CommonConstant.customerInputRedis,inputVo.toArray());
                    }
                }
                infoVo.setTagModuleList(tagModuleList);
                //如果是全量标签，代表这个客群什么活动都参与
                if ("4".equals(customerType)){
                    log.info("全量标签==="+activityId);
                    redisTemplate.opsForSet().add(CommonConstant.allActRedis,activityId);
                }else {
                    log.info("不是全量活动==="+activityId);
                    redisTemplate.opsForSet().add(CommonConstant.startActRedis,activityId);
                }
                //活动基本信息
                redisTemplate.opsForValue().set(activityId+"_"+CommonConstant.actBaseInfo, JSONObject.toJSONString(infoVo));
                pubBroadcastingActTaskMapper.updateActStatus(activityId,"1");
                log.info("开启活动成功:"+activityId);
            }
        }
    }

    /**
     * 停止公播平台活动
     */
    @Override
    public void stopActivity() {
        //查询要关闭的活动
        log.info("查询要关闭的活动");
        List<BroadcastActivityInfoVo> offAct = pubBroadcastingActTaskMapper.startOrStopAct("0");
        if (offAct !=null && offAct.size()>0){
            log.info("要关闭的活动个数:"+offAct.size());
            for(BroadcastActivityInfoVo infoVo:offAct){
                String activityId = infoVo.getActivityId();
                log.info("开始关闭:"+activityId);
                for (int i=1;i<5;i++){
                    BroadcastCustomerTagEnum byTagModule = BroadcastCustomerTagEnum.getByTagModule(String.valueOf(i));
                    String redisStr = byTagModule.getRedisStr();
                    redisTemplate.delete(activityId+"_"+redisStr);
                }
                redisTemplate.delete(activityId+"_"+CommonConstant.customerFileRedis);
                redisTemplate.delete(activityId+"_"+CommonConstant.customerInputRedis);
                redisTemplate.opsForSet().remove(CommonConstant.allActRedis,activityId);
                redisTemplate.opsForSet().remove(CommonConstant.startActRedis,activityId);
                redisTemplate.delete(activityId+"_"+CommonConstant.actBaseInfo);
                redisTemplate.opsForSet().add(CommonConstant.delActRedis,activityId);
                pubBroadcastingActTaskMapper.updateActStatus(activityId,"2");
                log.info("关闭活动成功:"+activityId);
            }
        }
    }
}
